package com.zklock;

import org.I0Itec.zkclient.IZkDataListener;

import java.util.concurrent.CountDownLatch;

/**
 * Created by yu756 on 2020/4/2 0:17
 */
public class ZkDistributedLock extends ZkAbstractTemplateLook {
    public boolean tryZkLock() {
        try {

            zkClient.createEphemeral(path);
            return true;
        } catch (Exception e) {
            return false;
        }


    }

    public boolean waitZkLock() {


        IZkDataListener iZkDataListener = new IZkDataListener() {
            public void handleDataChange(String s, Object o) throws Exception {
            }

            public void handleDataDeleted(String s) throws Exception {
                if (countDownLatch != null) {
                    countDownLatch.countDown();
                }


            }
        };
        zkClient.subscribeDataChanges(path, iZkDataListener);

        if (zkClient.exists(path)) {
            countDownLatch = new CountDownLatch(1);
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            zkClient.unsubscribeDataChanges(path, iZkDataListener);
        }


        return false;
    }
}
